import { Component, OnInit, HostListener } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { ListService } from '../_common/_service/list.service';
import { List } from '../_common/_model/list';
import { Task } from '../_common/_model/task';
import { User } from '../_common/_model/user';
import { NewListDto } from '../_common/_dtos/newListDto';
import { Functions } from '../_common/functions';
import { AppConsts } from '../_common/consts';
@Component({
  selector: 'app-sider',
  templateUrl: './sider.component.html',
  styleUrls: ['./sider.component.less']
})
export class SiderComponent implements OnInit {
  currentUrl: string;
  currentUser: User;
  menuItems: List[];
  myDayTasks: Task[];
  unFinish: number;

  contextmenuItem: List;
  contextmenuVisible = false;
  contextmenuX = 0;
  contextmenuY = 0;

  constructor(
    private _router: Router,
    private _funcs: Functions,
    private _listService: ListService,
    private _consts: AppConsts) { }

  ngOnInit() {
    this.getLists();
    // 初始化时获取当前路径 用于高亮对应的Menu
    this.currentUrl = this.getCurrentUrlWithoutQueryParams(this._router.url);
    // 发生路由跳转时更新currentUrl
    this._router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        this.currentUrl = this.getCurrentUrlWithoutQueryParams(event['urlAfterRedirects']);
      }
    });
    this.currentUser = this._funcs.getCurrentUser();
    this.getTodayTasks();
  }

  getLists() {
    if (!this._listService.lists) {
      setTimeout(() => {
        this.getLists();
      }, 300);
    } else {
      this.menuItems = this._listService.lists;
    }
  }

  getTodayTasks() {
    if (!this._listService.lists) {
      setTimeout(() => {
        this.getTodayTasks();
      }, 300);
    } else {
      this.myDayTasks = this._listService.getTodayTasks();
      // FIXME: 暂时先这样做。问题：当在其他清单标记了某个已是[我的一天]事项时，sider栏我的一天右边显示的undo数无法改变
      const isDoneArray = this.myDayTasks.filter(u => !u.isDone );
      this.unFinish = isDoneArray.length;
    }
  }

  getCurrentUrlWithoutQueryParams(url) {
    const index = url.indexOf('?');
    return index === -1
      ? url
      : url.substring(0, index);
  }

  addList(): void {
    const newList: NewListDto = {
      title: '无标题清单',
      icon: 'list',
      userId: this.currentUser.id
    };
    this._listService.addNewList(newList)
      .subscribe(list => {
        this.menuItems.push(list);
        this._router.navigate([`/lists/${list.id}`], { queryParams: { newlist: true } });
      });
  }

  isDefaultIcon(icon): boolean {
    return this._funcs.isDefaultIcon(icon);
  }

  handleContextmenu(e: MouseEvent, item) {
    this.contextmenuItem = item;
    this.contextmenuVisible = true;
    this.contextmenuX = e.clientX;
    this.contextmenuY = e.clientY;
    e.preventDefault();
  }

  @HostListener('document:click') closeContextmenu() {
    this.contextmenuVisible = false;
  }

}
